package de.pcsoft.framework.jclr;

import de.pcsoft.framework.jclr.exceptions.JCLRConfigurationException;
import org.xml.sax.SAXException;

import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.SchemaFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * JCLR Utils
 * User: Christoph
 * Date: 13.06.12
 * Time: 20:14
 */
public class JCLRUtils {

    /**
     * Load a configuration from the given stream
     *
     * @param in
     * @return
     * @throws JCLRConfigurationException
     */
    public static JCLRConfiguration loadConfiguration(InputStream in) throws JCLRConfigurationException {
        try {
            JAXBContext context = JAXBContext.newInstance(JCLRConfiguration.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            unmarshaller.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(
                    Thread.currentThread().getContextClassLoader().getResource("jclr.xsd")
            ));
            return (JCLRConfiguration) unmarshaller.unmarshal(in);
        } catch (JAXBException e) {
            throw new JCLRConfigurationException("Cannot load configuration file!", e);
        } catch (SAXException e) {
            throw new JCLRConfigurationException("Cannot load configuration file!", e);
        }
    }

    public static JCLRConfiguration loadConfiguration(File f) throws JCLRConfigurationException {
        try {
            return loadConfiguration(new FileInputStream(f));
        } catch (FileNotFoundException e) {
            throw new JCLRConfigurationException("Cannot load configuration file!", e);
        }
    }

}
